{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Queue Using Two Stacks\n",
    "\n",
    "[The Original Question](https://mp.weixin.qq.com/s/npnPG5E6NOcv_sutFezzoQ)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question\n",
    "\n",
    "> A queue is a data structure that supports the *FIFO protocol* (First in, first out).\n",
    "\n",
    "Implement a queue class using two stacks. Your class should support the enqueue and dequeue methods like a standard queue."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Queue:\n",
    "    def __init__(self):\n",
    "        # Initialize 2 stacks.\n",
    "        self.stack_A = list()\n",
    "        self.stack_B = list()\n",
    "\n",
    "    def push(self, val):\n",
    "        # Push the elements into one stack.\n",
    "        self.stack_A.append(val)\n",
    "\n",
    "    def pop(self):\n",
    "        # If the other stack is not empty,\n",
    "        # pop it directly.\n",
    "        if len(self.stack_B) != 0:\n",
    "            return self.stack_B.pop()\n",
    "        # If the first stack is empty,\n",
    "        # the whole queue is empty.\n",
    "        elif len(self.stack_A) == 0:\n",
    "            # Raise an exception.\n",
    "            raise IndexError('Index out of range!')\n",
    "        else:\n",
    "            while len(self.stack_A) != 0:\n",
    "                # When poping elements into another stack,\n",
    "                # all elements will be reversed.\n",
    "                self.stack_B.append(self.stack_A.pop())\n",
    "            return self.stack_B.pop()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "q = Queue()\n",
    "q.push(1)\n",
    "q.push(2)\n",
    "print(q.pop())\n",
    "q.push(3)\n",
    "print(q.pop())\n",
    "print(q.pop())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
